import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'dart:io';
import '../models/essay_material.dart';
import '../repositories/essay_material_repository.dart';
import 'add_edit_essay_material_screen.dart';
import '../widgets/image_preview_widget.dart';

class EssayMaterialListScreen extends StatefulWidget {
  const EssayMaterialListScreen({super.key});

  @override
  State<EssayMaterialListScreen> createState() => _EssayMaterialListScreenState();
}

class _EssayMaterialListScreenState extends State<EssayMaterialListScreen> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  bool _isLoading = true;
  
  // 分类数据
  final List<String> _categories = [
    '人物素材',
    '社会热点',
    '环境保护',
    '科技发展',
    '文化传承',
  ];
  
  // 素材数据（按分类）
  final Map<String, List<EssayMaterial>> _materialsByCategory = {};
  
  // 创建仓库实例
  final _essayMaterialRepository = EssayMaterialRepository();
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _categories.length, vsync: this);
    _loadMaterials();
  }
  
  Future<void> _loadMaterials() async {
    setState(() => _isLoading = true);
    
    try {
      // 初始化每个分类的素材列表
      for (final category in _categories) {
        _materialsByCategory[category] = [];
      }
      
      // 从数据库加载所有素材
      final allMaterials = await _essayMaterialRepository.getAllEssayMaterials();
      
      // 不再创建示例素材
      
      // 将素材按分类添加到对应列表
      for (final material in allMaterials) {
        final category = material.category;
        if (_materialsByCategory.containsKey(category)) {
          _materialsByCategory[category]!.add(material);
        } else if (_categories.isNotEmpty) {
          // 如果分类不存在，添加到第一个分类
          _materialsByCategory[_categories.first]!.add(material);
        }
      }
      
      setState(() => _isLoading = false);
    } catch (e) {
      print('加载素材错误: $e'); // 添加错误日志
      setState(() => _isLoading = false);
      _showErrorSnackBar('加载素材失败: $e');
    }
  }
  
  void _deleteMaterial(int id, String category) async {
    try {
      // 从数据库删除素材
      await _essayMaterialRepository.deleteEssayMaterial(id);
      
      setState(() {
        _materialsByCategory[category]?.removeWhere((material) => material.id == id);
      });
      
      _showSuccessSnackBar('素材已删除');
    } catch (e) {
      print('删除素材错误: $e'); // 添加错误日志
      _showErrorSnackBar('删除素材失败: $e');
    }
  }
  
  void _showDeleteConfirmDialog(int id, String category) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除素材'),
        content: const Text('确定要删除这个素材吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _deleteMaterial(id, category);
            },
            child: const Text('删除'),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
          ),
        ],
      ),
    );
  }
  
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }
  
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }
  
  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('作文素材库'),
        centerTitle: true,
        bottom: TabBar(
          controller: _tabController,
          isScrollable: true,
          tabs: _categories.map((category) => Tab(text: category)).toList(),
        ),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : TabBarView(
              controller: _tabController,
              children: _categories.map((category) {
                final materials = _materialsByCategory[category] ?? [];
                
                return materials.isEmpty
                    ? Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            const Icon(Icons.article_outlined, size: 64, color: Colors.grey),
                            const SizedBox(height: 16),
                            Text('暂无$category', style: const TextStyle(fontSize: 18, color: Colors.grey)),
                            const SizedBox(height: 24),
                          ],
                        ),
                      )
                    : ListView.builder(
                        padding: const EdgeInsets.all(16),
                        itemCount: materials.length,
                        itemBuilder: (context, index) {
                          final material = materials[index];
                          return Card(
                            margin: const EdgeInsets.only(bottom: 16),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                ListTile(
                                  title: Text(
                                    material.title,
                                    style: const TextStyle(fontWeight: FontWeight.bold),
                                  ),
                                  subtitle: Text(
                                    '创建于: ${_formatDate(DateTime.fromMillisecondsSinceEpoch(material.createdAt))}',
                                    style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                                  ),
                                  trailing: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      IconButton(
                                        icon: const Icon(Icons.edit_outlined),
                                        onPressed: () async {
                                          // 导航到编辑页面，并等待结果
                                          final result = await Navigator.of(context).push(
                                            MaterialPageRoute(
                                              builder: (context) => AddEditEssayMaterialScreen(
                                                materialId: material.id,
                                              ),
                                            ),
                                          );
                                          
                                          // 如果返回结果为true，刷新列表
                                          if (result == true) {
                                            _loadMaterials();
                                          }
                                        },
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.delete_outline),
                                        onPressed: () => _showDeleteConfirmDialog(material.id!, category),
                                      ),
                                    ],
                                  ),
                                ),
                                // 显示图片（如果有）
                                if (material.imageUrl != null && material.imageUrl!.isNotEmpty)
                                  Padding(
                                    padding: const EdgeInsets.symmetric(horizontal: 16.0),
                                    child: ImagePreviewWidget(
                                      imageUrl: material.imageUrl!,
                                      height: 150,
                                      width: double.infinity,
                                      fit: BoxFit.contain,
                                      showPath: false,
                                    ),
                                  ),
                                Padding(
                                  padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        material.content,
                                        maxLines: 3,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                      const SizedBox(height: 8),
                                      Align(
                                        alignment: Alignment.centerRight,
                                        child: TextButton(
                                          onPressed: () => context.push(
                                            '/profile/essay-materials/detail/${material.id}?fromTabIndex=${_tabController.index}',
                                          ),
                                          child: const Text('查看详情'),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                      );
              }).toList(),
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          // 导航到添加页面，并等待结果
          final result = await Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => const AddEditEssayMaterialScreen(),
            ),
          );
          
          // 如果返回结果为true，刷新列表
          if (result == true) {
            _loadMaterials();
          }
        },
        child: const Icon(Icons.add),
      ),
    );
  }
  
  String _formatDate(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')}';
  }
}